package me.xiaoyan.ehr.controller;

import me.xiaoyan.ehr.dao.LoginUserRepository;
import me.xiaoyan.ehr.util.StringUtil;
import me.xiaoyan.ehr.vo.LoginUser;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

public abstract class BaseController {
    @Resource
    private LoginUserRepository loginUserRepository;
    private static final String LOGIN_TOKEN_KEY = "token";

    protected int getLoginEmployeeId() {
        LoginUser loginUser = this.getLoginUser();
        return loginUser == null ? 0 : loginUser.getId();
    }

    protected LoginUser getLoginUser() {

        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String token = request.getHeader(LOGIN_TOKEN_KEY);

        if (StringUtil.isEmpty(token)) {
            return null;
        }
        Optional<LoginUser> optionalLoginUser = loginUserRepository.findById(token);
        if (optionalLoginUser.isPresent()) return optionalLoginUser.get();
        return null;
    }
}
